package com.three.common.message.base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.Packet;
import com.three.protocol.BaseModule;

import java.util.Arrays;

import static com.three.protocol.CommandEnum.Command.LOGIN;

/**
 * Created by Mathua on 2017/5/26.
 */
public final class LoginRespMessage extends BaseMessage {
    private int heartbeat;// 心跳间隔

    public LoginRespMessage(Packet message, Connection connection) {
        super(message, connection);
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        System.out.println("body:" + Arrays.toString(body));
        BaseModule.LoginResp_2 bodyData = BaseModule.LoginResp_2.parseFrom(body);
        heartbeat = bodyData.getHeartbeat();
    }

    @Override
    public byte[] encode() {
        BaseModule.LoginResp_2.Builder builder = BaseModule.LoginResp_2.newBuilder();
        builder.setHeartbeat(heartbeat);
        builder.setTimestamp(System.currentTimeMillis());
        return builder.build().toByteArray();
    }

    public static LoginRespMessage from(BaseMessage src) {
        return new LoginRespMessage(src.packet.response(LOGIN), src.connection);
    }

    public LoginRespMessage setHeartbeat(int heartbeat) {
        this.heartbeat = heartbeat;
        return this;
    }

    @Override
    public String toString() {
        return "HandshakeOkMessage{" +
                ", heartbeat=" + heartbeat +
                ", packet=" + packet +
                '}';
    }
    public int getHeartbeat() {
        return heartbeat;
    }
}
